#include <daemon.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

int daemonize(void) {
	pid_t pid, sid;
	if(getppid() == 1) return 0; /* already a daemon, our parent is init */
	
	pid = fork();
	if(pid < 0) return -1;
	if(pid) exit(0); /* exit the parent process now */
	
	/* this is all child code */
	umask(0); /* file mode mask change */
	if((sid = setsid()) < 0) return -1; /* set the SID */
	if((chdir("/")) < 0) return -1; /* change the directory to root */
	
	/* home stretch; redirect our standard outputs. no longer can we return -1 */
	freopen("/dev/null", "w", stdout);
	freopen("/dev/null", "w", stderr);
	freopen("/dev/null", "r", stdin);
	
	return 0;
}
